<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/8/6 20:09
 * Modified Time: 2019/8/6 20:09
 * Version: 2.0
 */

namespace App\Modules\Inventory\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Illuminate\Support\Facades\DB;

class GetSellGoodsListCriteria extends BaseCriterias
{
    protected $store_id;
    protected $keywords;

    public function __construct($store_id, $keywords)
    {
        $this->store_id = $store_id;
        $this->keywords = $keywords;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $store_id = $this->store_id;
        $keywords = $this->keywords;
        $model = $model
            ->select([
                'id',
                'store_id',
                'cat_id',
                'name',
                'small_name',
                'buying_price',
                'market_price',
                'royalty',
                'specs',
                'volume',
                'created_at',
                'image',
            ])
            ->with(['image'=>function($query){
                $query->select([
                    'id','image'
                ]);
            }])
            ->with(['goodsCategory'=>function($query){
                $query->select([
                    'id',
                    'parent_id',
                    'name'
                ])->with(['parent'=>function($query){
                    $query->select([
                        'id',
                        'parent_id',
                        'name'
                    ]);
                }]);
            }])
            ->withCount(['goodsOrder'])
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('goods.name', 'like', '%' . $keywords . '%');
            })
            ->where('goods.store_id', $store_id)
            ->where('goods.is_sell', 1)
            ->orderBy('id','DESC');

        return $model;
    }
}